package org.qydjk.common.util;


import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

public class StringUtil {
    /**
     * iso-8859-1转utf-8
     * @param source
     * @return
     */
    public static String iosToUTF8(String source){
        try {
            return new String(source.getBytes("iso-8859-1"),"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 头尾去逗号
     * @param source
     * @return
     */
    public static String dotWipeStartEnd(String source){
       if(!isEmptyOrNull(source)){
           if(source.startsWith(",")){
               source = source.substring(1,source.length());
           }
           if(source.endsWith(",")){
               source = source.substring(0,source.length() - 1);
           }
           return source;
       }
       return source;
    }

    /**
     * 头尾加逗号
     * @param source
     * @return
     */
    public static String dotAddStartEnd(String source){
        if(!isEmptyOrNull(source)){
            if(!source.startsWith(",")){
                source = "," + source;
            }
            if(!source.endsWith(",")){
                source = source + ",";
            }
            return source;
        }
        return source;
    }

    /**
     * 字符串为空
     * @param str
     * @return
     */
    public static boolean isEmptyOrNull(String str){
        if(str == null || str.equals("")){
            return true;
        }
        return false;
    }

    /**
     * 数组为空
     * @param list
     * @return
     */
    public static boolean isEmptyOrNull(Collection list){
        if(list == null || list.size() <= 0){
            return true;
        }
        return false;
    }
    /**
     * 生成uuid
     * @return UUID
     */
    public static String getUUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * 数组转1,2,3,4
     * @return
     */
    public static String intListToInSQL(List<Integer> list){
            if(list == null || list.size() <= 0){
            return "";
        }else if(list.size() == 1){
            return list.get(0).toString();
        }else{
            StringBuffer ids = new StringBuffer("");
            for (Integer id:  list) {
                ids.append(id.toString()).append(",");
            }
            String res = ids.substring(0, ids.length() - 1);
            return res;
        }
    }

    /**
     * 转换为下划线
     *
     * @param camelCaseName
     * @return
     */
    public static String underscoreName(String camelCaseName) {
        StringBuilder result = new StringBuilder();
        if (camelCaseName != null && camelCaseName.length() > 0) {
            result.append(camelCaseName.substring(0, 1).toLowerCase());
            for (int i = 1; i < camelCaseName.length(); i++) {
                char ch = camelCaseName.charAt(i);
                if (Character.isUpperCase(ch)) {
                    result.append("_");
                    result.append(Character.toLowerCase(ch));
                } else {
                    result.append(ch);
                }
            }
        }
        return result.toString();
    }

    /**
     * 转换为驼峰
     *
     * @param underscoreName
     * @return
     */
    public static String camelCaseName(String underscoreName) {
        StringBuilder result = new StringBuilder();
        if (underscoreName != null && underscoreName.length() > 0) {
            boolean flag = false;
            for (int i = 0; i < underscoreName.length(); i++) {
                char ch = underscoreName.charAt(i);
                if ("_".charAt(0) == ch) {
                    flag = true;
                } else {
                    if (flag) {
                        result.append(Character.toUpperCase(ch));
                        flag = false;
                    } else {
                        result.append(ch);
                    }
                }
            }
        }
        return result.toString();
    }

    /**
     * MD5加密
     * @param s
     * @return
     */
    public final static String encodeMd5(String s) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f' };
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] md5Password = md5.digest(s.getBytes());
            int j = md5Password.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md5Password[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 格式化距离  大于1000m单位为km
     * @param distance
     * @return
     */
    public static String formatDistance(Double distance){
        String retString = null;
        if (distance != null) {
            if (distance >= 1) {
                String strDistance = String.valueOf(distance);
                int index = strDistance.indexOf(".");
                retString = strDistance.substring(0, index + 2)+"km";
            } else {
                retString = new BigDecimal(distance*1000).setScale(0, RoundingMode.HALF_UP).toString()+"m";

            }
        }
        return retString;

    }

    /**
     * Unicode转中文
     * @param dataStr
     * @return
     */
    public static String decodeUnicode(final String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }

    /**
     * 中文转Unicode
     * @param gbString
     * @return
     */
    public static String encodeUnicode(final String gbString) {
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
            String hexB = Integer.toHexString(utfBytes[byteIndex]);   //转换为16进制整型字符串
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        System.out.println("unicodeBytes is: " + unicodeBytes);
        return unicodeBytes;
    }

}
